<?php

class ControllerToolLycTool extends Controller {

	//初始化
	public function index() {

		$this->load->language('tool/lyctool');
		$this->document->setTitle($this->language->get('heading_title'));
		$this->load->model('tool/lyctool');
		
		$data['heading_title'] = $this->language->get('heading_title');

		$data['breadcrumbs'] = array();
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('tool/lyctool', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		$data['rebuildProductAction'] = $this->url->link('tool/lyctool/rebuildProductIndex', 'token=' . $this->session->data['token'], 'SSL');

		$data['rebuildWxappAction'] = $this->url->link('tool/lyctool/rebuildWxappShopProducts', 'token=' . $this->session->data['token'], 'SSL');

		$data['couponAction'] = $this->url->link('tool/lyctool/addCoupon', 'token=' . $this->session->data['token'], 'SSL');

		if(isset($this->error['warning'])){
			$data['error_warning'] = $this->error['warning'];
		}
		else{
			$data['error_warning'] = '';
		}

		if(isset($this->session->data['success'])){
			$data['success'] = $this->session->data['success'];
			unset($this->session->data['success']);
		}
		else{
			$data['success'] = '';
		}

		$data['token'] = $this->session->data['token'];

		//加载头部侧边栏底部
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		//返回模板页
		$this->response->setOutput($this->load->view('tool/lyctool.tpl', $data));

    }
	
	//重建商城商品索引
	public function rebuildProductIndex(){
		
		$this->load->language('tool/lyctool');
		$this->load->model('tool/lyctool');

		$this->model_tool_lyctool->rebuildProductIndex();

		$this->session->data['success'] = $this->language->get('text_rebuild_success');

		$this->response->redirect($this->url->link('tool/lyctool', 'token=' . $this->session->data['token'] . $url, 'SSL'));

	}

	//重建小程序搜索商铺商品索引
	public function rebuildWxappShopProducts(){
		
		$this->load->language('tool/lyctool');
		$this->load->model('tool/lyctool');

		$this->model_tool_lyctool->rebuildWxappShopProducts();

		$this->session->data['success'] = $this->language->get('text_rebuild_success');

		$this->response->redirect($this->url->link('tool/lyctool', 'token=' . $this->session->data['token'] . $url, 'SSL'));

	}

	//用户手机autocomplete
	public function autoTel() {
		
		$json = array();

		if (isset($this->request->get['tel'])) {
			$filter_tel = trim($this->request->get['tel']);
		}
		else{
			$filter_tel = '';
		}

		$filter_data = array(
			'filter_tel' => $filter_tel,
			'start' => 0,
			'limit' => 5
		);

		$this->load->model('tool/lyctool');

		$results = $this->model_tool_lyctool->getCustomers($filter_data);

		foreach ($results as $result){
			$json[] = array(
				'customer_id' => $result['customer_id'],
				'telephone' => $result['telephone']
			);
		}
		
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));

	}

	//添加优惠券
	public function addCoupon(){
		
		$tel = $this->request->post['c_tel'];
		$customer_id = $this->request->post['c_id'];

		
		$price = $this->request->post['c_coupon']; 
		$total = 0;
		$days = $this->request->post['c_days']-1; //因为优惠包括当天所以天数要减1天 
		$number = $this->request->post['c_number']; 
		
		$this->createCoupon($customer_id,'奖券',$price,$total,$days,$number);

		$this->session->data['success'] = $this->language->get('添加成功');
		$this->response->redirect($this->url->link('tool/lyctool', 'token=' . $this->session->data['token'] . $url, 'SSL'));
	
	}

	//产生优惠券
	public function createCoupon($customer_id,$name,$price,$total,$days,$number) {
		
		$this->load->model('marketing/coupon');

		$data['name'] = $name;
		$data['type'] = 'F';
		$data['discount'] = $price;
		$data['total'] = $total;
		$data['logged'] = 1;
		$data['shipping'] = 0;
		$data['date_start'] = date('Y-m-d H:i:s');
		$data['date_end'] = date('Y-m-d H:i:s', time()+3600*24*$days);
		$data['uses_total'] = 1;
		$data['uses_customer'] = 1;
		$data['status'] = 1;
		$data['number'] = $number;
		$this->model_marketing_coupon->addCouponToCustomer($customer_id, $data);

	}
	


	//导入用户组特价

	public function importproSpeXial() {
	    $json = array();
	    if (1) {
	      if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
	        // Sanitize the filename
	        $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
	        // Validate the filename length
	        if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
	          $json['error'] = '文件名过短';
	        }
	        // Allowed file extension types
	        $allowed = array('xls','xlsx');
	        if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
	          $json['error'] = '请上传xls或者xlsx文件';
	        }
	        // Return any upload error
	        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
	          $json['error'] = '上传出现错误';
	        }
	      } 
	    }
	    else {
	      $json['error'] = '上传失败';
	    }

	    if (!$json) {
	      $this->load->library('PHPExcel/PHPExcel');
	      $savePath = $this->request->files['file']['tmp_name'];
	      $PHPExcel = new PHPExcel();
	      $PHPReader = new PHPExcel_Reader_Excel2007();
	      if(!$PHPReader->canRead($savePath)){
	        $PHPReader = new PHPExcel_Reader_Excel5();
	      }
	      $PHPExcel = $PHPReader->load($savePath);
	      $sheetCount = $PHPExcel->getSheetCount();
	      // var_dump($sheetCount);die();
	      $j=0;
	      $data = [];
	    for ( $i = 0; $i < $sheetCount; $i++ ) {
	     	// echo $i;
		    $currentSheet = $PHPExcel->getSheet($i);
		    $allRow = $currentSheet->getHighestRow();
		      // var_dump($allRow);
		      //获取order_product_id, express_name, express_number在excel中的index
		    $pcode_idx = 'A';
		    $price_idx = 'B';
		      
		    $this->load->model('catalog/product');
		    $products_info = array();
		    for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
				// echo $j;
				// echo '<br>';
				$j++;
				$pcode = (String)$currentSheet->getCell($pcode_idx.$currentRow)->getValue();
				$price = (String)$currentSheet->getCell($price_idx.$currentRow)->getValue();


				//检查sku是否存在
				$product = M('product')->where( array('product_code' =>$pcode))->find();
				// echo M('product_option_value')->getlastsql();
				// var_dump($product['product_code']);
				if(empty($product)) {
				$json['error'] = '第' . $currentRow . '行条码对应商品未找到';
				var_dump($json['error']);die();
				}
				if(empty($price)) {
						var_dump($json['error']);die();
				}

				$data[$product['product_code']]['pcode'] = $product['product_code'];
				$data[$product['product_code']]['price'] = $price;
				$data[$product['product_code']]['product_id'] = $product['product_id'];
				// var_dump($data);die();

			}
				
		  } 
		}
		foreach ($data as $key => $value) {
		   	$spdata = array(
		   		'product_id' =>$value['product_id'] ,
		   		'customer_group_id' => 2,
		   		'price' => $value['price'] ,
		   		'date_start' => date("Y-m-d"),
		   		'date_end' => '2050-01-01',
		   		 );
		   	M('product_special')->add($spdata);
		}   


	  }


}
?>